/**
 * Create by Wanglei
 * */

(function ($) {
    var dataName="filePath";
    var elemClass="sheyi-gallery";
    $.fancybox.defaults.tpl.error='<p class="fancybox-error">找不到该图片路径。<br/>请重新上传或联系管理员。</p>';
    // 验证jQuery对象是否为gallery
    function validate($elem){
        return $elem.hasClass(elemClass);
    }
    function appendFile(opts,$gallery,filePath,fileName){
        if(opts.type==="file" && _.isEmpty(fileName)){
            fileName=filePath.substring(filePath.lastIndexOf("/")+1);
        }
        var wholePath=window.fileHost+common.decodeHTML(filePath);
        var $delImageBtn=$("<i>").addClass("fa fa-2x fa-trash-o pull-right delete-button");
        var $delFileBtn=$("<i>").addClass("fa fa-2x fa-trash-o padding-em-left text-danger delete-button");
        if(opts.type==="image"){
            var $fancybox=$("<a>").addClass("fancybox file-path").prop({href:wholePath}).data(dataName,filePath);
            $fancybox.append($("<img>").prop({src:wholePath}));
            if(!opts.readOnly){
                $fancybox.append($("<div>").addClass("overlay").append($delImageBtn));
            }
            if(!!filePath){
                $gallery.append($fancybox);
                $(".fancybox").fancybox();
            }
        }else if(opts.type==="audio"){
            var audioPath = filePath.indexOf("http")>-1? filePath : window.audioFileHost+filePath;
            var $file=$("<a>").addClass("file-path").prop({href:audioPath,target:"_blank"}).data(dataName,audioPath).text(fileName);
            if(!opts.readOnly){
                $file.append($delFileBtn)
            }
            $gallery.append($("<div>").addClass("row").append($file));
        }else{
            var $file=$("<a>").addClass("file-path").prop({href:wholePath,target:"_blank"}).data(dataName,filePath).text(fileName);
            if(!opts.readOnly){
                $file.append($delFileBtn)
            }
            $gallery.append($("<div>").addClass("row").append($file));
        }
    }
    /**
     * 基于fancybox,jQuery的简单图库插件
     * @param {Boolean} [options.readOnly=false] 是否只读
     * @param {String} [options.type=image] 相册类型，支持image／图片和file／文件
     * @param {String} [options.title=文件上传] 标题
     * @param {String} options.url 上传url
     * @param {String} [options.paramName=file] 文件上传的参数名
     * @param {String} [options.returnPathName=filePath] 返回文件路径参数名
     * @param {Object} options.fileFolder 前端路径
     * @param {Number} [options.maxFiles=100] 最大文件数 
     * @param {Number} [options.maxFileSize=10] 单文件最大容量
     * @param {String[]} [options.filePaths] 已存在文件名列表
     * @param {Function} [options.uploadCallback] 上传完成后的回调函数 
     * @param {Function} [options.deleteCallback] 删除完成后的回调函数
     */
    $.fn.gallery = function (options) {
        var opts=$.extend({},$.fn.gallery.defaults,options);
        if(!opts.readOnly){
            $(this).on("click",".delete-button",function(ev){
                var $recordEle=$(this).parents("a");
                var filePath=$recordEle.data(dataName);
                $recordEle.removeData(dataName).remove();
                if(opts.deleteCallback){
                    opts.deleteCallback(filePath);
                }
                ev.stopPropagation();
                return false;
            });
        }
        var that=this;
        that.addClass(elemClass);
        var $container=$("<div>");
        var $topPanel=$("<div>").addClass("row").append(
            "<span class='col-sm-6'><h4>"+opts.title+"<small class='padding-em-left'>最大文件数："+opts.maxFiles+"&nbsp;&nbsp;每张最大"+opts.maxFileSize+"M</small></h4></span>"
        );
        var $uplaodButton=$("<button>").prop({type:"button"}).addClass("btn btn-link").text("点击上传").css({display:"inline-block"});
        if(!opts.readOnly){
            $topPanel.append($uplaodButton);
        }
        $container.append($topPanel);
        var $gallery=$("<div>").addClass("ibox-content");
        opts.filePaths.forEach(function(filePath){
            if(opts.type == 'image'){
                appendFile(opts,$gallery,filePath);
            }else{
                var fileName=filePath.substring(filePath.lastIndexOf("/")+1);
                appendFile(opts,$gallery,filePath,fileName);
            }
        });
        var $galleryPanel=$("<div>").append($gallery);
        $container.append($galleryPanel).appendTo(that);

        if(!opts.readOnly){
            $uplaodButton.on("click",function(){
                var uploadedFilesCount=that.getFilePaths().length;
                if(uploadedFilesCount>=opts.maxFiles){
                    layer.alert("已上传文件已经达到上限。不能继续上传。");
                    return;
                }
                var layerIdx;
                var uploadOptions={
                    url:opts.url,
                    paramName:opts.paramName,
                    fileFolder:opts.fileFolder,
                    maxFiles:opts.maxFiles-uploadedFilesCount,
                    type:opts.type,
                    success:function(file,data){
                        if(data.code == 0) {
                            layer.close(layerIdx);
                        }
                        // console.log("gallery success");
                        var returnData=common.transformData(data);
                        // transformData will show the error message itself
                        if(_.isEmpty(returnData)) return;
                        var filePath=returnData[opts.returnPathName];
                        // layer.close(layerIdx);
                        appendFile(opts,$gallery,filePath,file.name);
                        if(opts.uploadCallback){
                            opts.uploadCallback(filePath);
                        }
                        var msg = data["res"]["msg"];
                        layer.alert(msg);
                    }
                };
                layerIdx=common.upload(uploadOptions);
            });
        }

        return that;
    };

    $.fn.gallery.defaults={
        readOnly:false,
        paramName:"file",
        title:"文件上传",
        fileFolder:"image",
        filePaths:[],
        returnPathName:"filePath",
        type:"image",
        maxFiles:20,
        maxFileSize:20
    };

    $.fn.getFilePaths=function(){
        if(!validate(this)) return;
        var rstPaths=[];
        var $filePaths=this.find("a.file-path");
        $filePaths.each(function(){
            rstPaths.push($(this).data(dataName));
        });
        return rstPaths;
    };
    $.fn.getFileNames=function(){
        if(!validate(this)) return;
        var rstNames=[];
        var $filePaths=this.find("a.file-path");
        $filePaths.each(function(){
            rstNames.push($(this).text());
        });
        return rstNames;
    };

})(jQuery);